package com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.repository.HddcGeomorphysvylineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.repository.HddcGeomorphysvylineRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.repository.entity.HddcGeomorphysvylineEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyLine.repository.HddcWyGeomorphysvylineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyLine.repository.HddcWyGeomorphysvylineRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyLine.repository.entity.HddcWyGeomorphysvylineEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyLine.service.HddcWyGeomorphysvylineService;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyLine.viewobjects.HddcWyGeomorphysvylineQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyGeomorphySvyLine.viewobjects.HddcWyGeomorphysvylineVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.*;

/**
 * @author lihelei
 * @date 2020-12-01
 */
@Service
public class HddcWyGeomorphysvylineServiceImpl implements HddcWyGeomorphysvylineService {

    @Autowired
    private HddcWyGeomorphysvylineRepository hddcWyGeomorphysvylineRepository;
    @Autowired
    private HddcWyGeomorphysvylineNativeRepository hddcWyGeomorphysvylineNativeRepository;
    @Autowired
    private HddcGeomorphysvylineRepository hddcGeomorphysvylineRepository;
    @Autowired
    private HddcGeomorphysvylineNativeRepository hddcGeomorphysvylineNativeRepository;

    @Override
    public JSONObject queryHddcWyGeomorphysvylines(HddcWyGeomorphysvylineQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyGeomorphysvylineEntity> hddcWyGeomorphysvylinePage = this.hddcWyGeomorphysvylineNativeRepository.queryHddcWyGeomorphysvylines(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyGeomorphysvylinePage);
        return jsonObject;
    }


    @Override
    public HddcWyGeomorphysvylineEntity getHddcWyGeomorphysvyline(String uuid) {
        HddcWyGeomorphysvylineEntity hddcWyGeomorphysvyline = this.hddcWyGeomorphysvylineRepository.findById(uuid).orElse(null);
        return hddcWyGeomorphysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeomorphysvylineEntity saveHddcWyGeomorphysvyline(HddcWyGeomorphysvylineEntity hddcWyGeomorphysvyline) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyGeomorphysvyline.setUuid(uuid);
        if (StringUtils.isEmpty(hddcWyGeomorphysvyline.getCreateUser())) {
            hddcWyGeomorphysvyline.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyGeomorphysvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyGeomorphysvyline.setIsValid("1");

        HddcGeomorphysvylineEntity hddcGeomorphysvylineEntity = new HddcGeomorphysvylineEntity();
        BeanUtils.copyProperties(hddcWyGeomorphysvyline, hddcGeomorphysvylineEntity);
        hddcGeomorphysvylineEntity.setExtends4(hddcWyGeomorphysvyline.getTown());
        hddcGeomorphysvylineEntity.setExtends5(String.valueOf(hddcWyGeomorphysvyline.getLon()));
        hddcGeomorphysvylineEntity.setExtends6(String.valueOf(hddcWyGeomorphysvyline.getLat()));
        this.hddcGeomorphysvylineRepository.save(hddcGeomorphysvylineEntity);

        this.hddcWyGeomorphysvylineRepository.save(hddcWyGeomorphysvyline);
        return hddcWyGeomorphysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcWyGeomorphysvylineEntity> saveHddcWyGeomorphysvylineList(List<HddcWyGeomorphysvylineEntity> list) {
        List<HddcGeomorphysvylineEntity> hddcGeomorphysvylines = new ArrayList<>();
        for (HddcWyGeomorphysvylineEntity hddcWyGeomorphysvyline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcWyGeomorphysvyline.setUuid(uuid);
            if (StringUtils.isEmpty(hddcWyGeomorphysvyline.getCreateUser())) {
                hddcWyGeomorphysvyline.setCreateUser(PlatformSessionUtils.getUserId());
            }
            hddcWyGeomorphysvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcWyGeomorphysvyline.setIsValid("1");

            HddcGeomorphysvylineEntity hddcGeomorphysvylineEntity = new HddcGeomorphysvylineEntity();
            BeanUtils.copyProperties(hddcWyGeomorphysvyline, hddcGeomorphysvylineEntity);
            hddcGeomorphysvylineEntity.setExtends4(hddcWyGeomorphysvyline.getTown());
            hddcGeomorphysvylineEntity.setExtends5(String.valueOf(hddcWyGeomorphysvyline.getLon()));
            hddcGeomorphysvylineEntity.setExtends6(String.valueOf(hddcWyGeomorphysvyline.getLat()));
            hddcGeomorphysvylines.add(hddcGeomorphysvylineEntity);
        }
        hddcGeomorphysvylineNativeRepository.batchSave(hddcGeomorphysvylines);
        return hddcWyGeomorphysvylineNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeomorphysvylineEntity updateHddcWyGeomorphysvyline(HddcWyGeomorphysvylineEntity hddcWyGeomorphysvyline) {
        HddcWyGeomorphysvylineEntity entity = hddcWyGeomorphysvylineRepository.findById(hddcWyGeomorphysvyline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyGeomorphysvyline);
        hddcWyGeomorphysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyGeomorphysvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyGeomorphysvylineRepository.save(hddcWyGeomorphysvyline);
        return hddcWyGeomorphysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyGeomorphysvylines(List<String> ids) {
        List<HddcWyGeomorphysvylineEntity> hddcWyGeomorphysvylineList = this.hddcWyGeomorphysvylineRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcWyGeomorphysvylineList) && hddcWyGeomorphysvylineList.size() > 0) {
            for (HddcWyGeomorphysvylineEntity hddcWyGeomorphysvyline : hddcWyGeomorphysvylineList) {
                this.hddcWyGeomorphysvylineRepository.delete(hddcWyGeomorphysvyline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyGeomorphysvyline(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyGeomorphysvylineNativeRepository.queryHddcWyGeomorphysvyline(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyGeomorphysvylineEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyGeomorphysvylineEntity> list = hddcWyGeomorphysvylineRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyGeomorphysvylineEntity> hddcWyGeomorphysvylineEntity = hddcWyGeomorphysvylineNativeRepository.exportLine(queryParams);
        List<HddcWyGeomorphysvylineVO> list = new ArrayList<>();
        for (HddcWyGeomorphysvylineEntity entity : hddcWyGeomorphysvylineEntity) {
            HddcWyGeomorphysvylineVO hddcWyGeomorphysvylineVO = new HddcWyGeomorphysvylineVO();
            BeanUtils.copyProperties(entity, hddcWyGeomorphysvylineVO);
            list.add(hddcWyGeomorphysvylineVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "微地貌测量线-线", "微地貌测量线-线", HddcWyGeomorphysvylineVO.class, "微地貌测量线-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyGeomorphysvylineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyGeomorphysvylineVO.class, params);
            List<HddcWyGeomorphysvylineVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size()));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyGeomorphysvylineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyGeomorphysvylineVO hddcWyTrenchVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyTrenchVO.getRowNum() + "行" + hddcWyTrenchVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcWyGeomorphysvylineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyGeomorphysvylineEntity hddcWyGeomorphysvylineEntity = new HddcWyGeomorphysvylineEntity();
            HddcWyGeomorphysvylineVO hddcWyGeomorphysvylineVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyGeomorphysvylineVO, hddcWyGeomorphysvylineEntity);
            saveHddcWyGeomorphysvyline(hddcWyGeomorphysvylineEntity);
        }
    }


    @Override
    public List<HddcWyGeomorphysvylineEntity> findAllByCreateUserAndIsValid(String userId, String isValid) {
        List<HddcWyGeomorphysvylineEntity> list = hddcWyGeomorphysvylineRepository.findAllByCreateUserAndIsValid(userId, isValid);
        return list;
    }


    /**
     * 逻辑删除-根据项目id删除数据
     *
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyGeomorphysvylineEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeomorphysvylineRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcWyGeomorphysvylineEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeomorphysvylineRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     *
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyGeomorphysvylineEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeomorphysvylineRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if (!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for (HddcWyGeomorphysvylineEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeomorphysvylineRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }
}
